package com.alog.yzd.bookmall.web.servlet.order;

import com.alog.yzd.bookmall.domain.cart.CartItem;
import com.alog.yzd.bookmall.domain.order.Order;
import com.alog.yzd.bookmall.domain.order.OrderItem;
import com.alog.yzd.bookmall.domain.user.User;
import com.alog.yzd.bookmall.pager.PageBaen;
import com.alog.yzd.bookmall.service.cart.CartService;
import com.alog.yzd.bookmall.service.order.OrderService;
import com.alog.yzd.bookmall.utils.WebUtils;
import com.alog.yzd.commons.CommonUtils;
import com.alog.yzd.commons.Print;
import com.alog.yzd.commons.servlet.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

public class OrderServlet extends BaseServlet {
    private OrderService orderService = new OrderService();
    private CartService cartService = new CartService();

    /**
     * 支付响应(响应易宝)
     */
    public String back(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /*
         * 1. 获取12个参数
         */
        String p1_MerId = req.getParameter("p1_MerId");
        String r0_Cmd = req.getParameter("r0_Cmd");
        String r1_Code = req.getParameter("r1_Code");
        String r2_TrxId = req.getParameter("r2_TrxId");
        String r3_Amt = req.getParameter("r3_Amt");
        String r4_Cur = req.getParameter("r4_Cur");
        String r5_Pid = req.getParameter("r5_Pid");
        String r6_Order = req.getParameter("r6_Order");
        String r7_Uid = req.getParameter("r7_Uid");
        String r8_MP = req.getParameter("r8_MP");
        String r9_BType = req.getParameter("r9_BType");
        String hmac = req.getParameter("hmac");
        /*
         * 2. 获取keyValue
         */
        Properties props = new Properties();
        props.load(this.getClass().getClassLoader().getResourceAsStream("payment.properties"));
        String keyValue = props.getProperty("keyValue");

        boolean bool = PaymentUtil.verifyCallback(hmac, p1_MerId, r0_Cmd, r1_Code, r2_TrxId,
                r3_Amt, r4_Cur, r5_Pid, r6_Order, r7_Uid, r8_MP, r9_BType,
                keyValue);
        if(!bool) {
            req.setAttribute("code", "error");
            req.setAttribute("msg", "无效的签名，支付失败！（你不是好人）");
            return "f:/jsps/msg.jsp";
        }
        if(r1_Code.equals("1")) {
            orderService.updateStatus(r6_Order, 2);
            if(r9_BType.equals("1")) {
                req.setAttribute("code", "success");
                req.setAttribute("msg", "恭喜，支付成功！");
                return "f:/jsps/msg.jsp";
            } else if(r9_BType.equals("2")) {
                resp.getWriter().print("success");
            }
        }
        return null;
    }

    /**
     * 支付响应(响应易宝)
     */
    public String payment(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Properties props = new Properties();
        props.load(this.getClass().getClassLoader().getResourceAsStream("payment.properties"));
        /*
         * 1. 准备13个参数
         */
        String p0_Cmd = "Buy";//业务类型，固定值Buy
        String p1_MerId = props.getProperty("p1_MerId");//商号编码，在易宝的唯一标识
        String p2_Order = req.getParameter("oid");//订单编码
        String p3_Amt = "0.01";//支付金额
        String p4_Cur = "CNY";//交易币种，固定值CNY
        String p5_Pid = "";//商品名称
        String p6_Pcat = "";//商品种类
        String p7_Pdesc = "";//商品描述
        String p8_Url = props.getProperty("p8_Url");//在支付成功后，易宝会访问这个地址。
        String p9_SAF = "";//送货地址
        String pa_MP = "";//扩展信息
        String pd_FrpId = req.getParameter("yh");//支付通道
        String pr_NeedResponse = "1";//应答机制，固定值1

        String keyValue = props.getProperty("keyValue");
        String hmac = PaymentUtil.buildHmac(p0_Cmd, p1_MerId, p2_Order, p3_Amt,
                p4_Cur, p5_Pid, p6_Pcat, p7_Pdesc, p8_Url, p9_SAF, pa_MP,
                pd_FrpId, pr_NeedResponse, keyValue);

        /*
         * 3. 重定向到易宝的支付网关
         */
        StringBuilder sb = new StringBuilder("https://www.yeepay.com/app-merchant-proxy/node");
        sb.append("?").append("p0_Cmd=").append(p0_Cmd);
        sb.append("&").append("p1_MerId=").append(p1_MerId);
        sb.append("&").append("p2_Order=").append(p2_Order);
        sb.append("&").append("p3_Amt=").append(p3_Amt);
        sb.append("&").append("p4_Cur=").append(p4_Cur);
        sb.append("&").append("p5_Pid=").append(p5_Pid);
        sb.append("&").append("p6_Pcat=").append(p6_Pcat);
        sb.append("&").append("p7_Pdesc=").append(p7_Pdesc);
        sb.append("&").append("p8_Url=").append(p8_Url);
        sb.append("&").append("p9_SAF=").append(p9_SAF);
        sb.append("&").append("pa_MP=").append(pa_MP);
        sb.append("&").append("pd_FrpId=").append(pd_FrpId);
        sb.append("&").append("pr_NeedResponse=").append(pr_NeedResponse);
        sb.append("&").append("hmac=").append(hmac);

        resp.sendRedirect(sb.toString());

        return null;
    }

    /**
     * 支付准备
     */
    public String paymentPre(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String oid = req.getParameter("oid");
        Order order = orderService.load(oid);
        req.setAttribute("order", order);
        return "f:/jsps/order/pay.jsp";
    }


    /**
     * 确认收货
     */
    public String confirm(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String oid = req.getParameter("oid");
        int status = orderService.findStatus(oid);
        if(status == 3){
            orderService.updateStatus(oid, 4);
            req.setAttribute("code", "success");
            req.setAttribute("msg", "确认收货成功");
            return "f:/jsps/msg.jsp";
        } else {
            req.setAttribute("code", "error");
            req.setAttribute("msg", "状态不对, 不能确认收货");
            return "f:/jsps/msg.jsp";
        }
    }
    /**
     * 取消订单
     */
    public String cancel(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String oid = req.getParameter("oid");
        int status = orderService.findStatus(oid);
        if(status == 1){
            orderService.updateStatus(oid, 5);
            req.setAttribute("code", "success");
            req.setAttribute("msg", "订单取消成功");
            return "f:/jsps/msg.jsp";
        } else {
            req.setAttribute("code", "error");
            req.setAttribute("msg", "状态不对, 不能取消");
            return "f:/jsps/msg.jsp";
        }
    }

    /**
     * 加载订单
     */
    public String load(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String oid = req.getParameter("oid");
        Order order = orderService.load(oid);
        req.setAttribute("order", order);
        String btn = req.getParameter("btn");
        req.setAttribute("btn", btn);
        return "f:/jsps/order/desc.jsp";
    }
    /**
     * 创建订单
     */
    public String createOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String cartItemIds = req.getParameter("cartItemIds");
        String address = req.getParameter("address");
        User user = (User) req.getSession().getAttribute("sessionUser");
        List<CartItem> cartItems = cartService.loadCartItems(cartItemIds);
        Order order = generateOrder(cartItems, address, user);
        orderService.createOrder(order);

        cartService.batchDelete(cartItemIds);

        req.setAttribute("order", order);
        return "f:/jsps/order/ordersucc.jsp";
    }

    /**
     * 生成订单对象
     */
    private Order generateOrder(List<CartItem> cartItems, String address, User user){
        Order order = new Order();
        order.setOid(CommonUtils.uuid());
        order.setOrdertime(String.format("%tF %<tT", new Date()));
        order.setStatus(1);
        order.setAddress(address);
        order.setOwner(user);

        BigDecimal total = new BigDecimal("0");
        List<OrderItem> orderItems = new ArrayList<>();
        for(CartItem cartitem : cartItems){
            total = total.add(new BigDecimal(cartitem.getSubtotal() + ""));

            OrderItem orderItem = new OrderItem();
            orderItem.setOrder(order);
            orderItem.setOrderItemId(CommonUtils.uuid());
            orderItem.setQuantity(cartitem.getQuantity());
            orderItem.setSubtotal(cartitem.getSubtotal());
            orderItem.setBook(cartitem.getBook());
            orderItems.add(orderItem);
        }

        order.setTotal(total.doubleValue());
        order.setOrderItems(orderItems);
        return order;
    }

    /**
     * 我的订单
     * @param req
     * @param resp
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String myOrders(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int pc = WebUtils.getPc(req);
        String url = WebUtils.getUri(req);
        User user = (User) req.getSession().getAttribute("sessionUser");
        PageBaen<Order> pb = orderService.myOrders(user.getUid(), pc);
        pb.setUrl(url);
        req.setAttribute("pb", pb);
        Print.print("findByUser, pb:" + pb);
        return "f:/jsps/order/list.jsp";
    }

}
